package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.util.R;
import cn.wolfcode.rbac.util.RedisKey;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(handler.getClass());
        //进行登录的判断
        //1.获取请求头是否有Token的信息，如果没有Token，直接返回,拒绝请求.
        String token = request.getHeader("token");
        //2.从Redis中查询是否有该Key，如果有就放行
        String tokenKey = RedisKey.TOKEN_PREFIX+token;
        if(StringUtils.isEmpty(token) || !stringRedisTemplate.hasKey(tokenKey)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(R.fail(401,"认证信息有误")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String token = request.getHeader("token");
        String tokenKey = RedisKey.TOKEN_PREFIX+token;
        if(!StringUtils.isEmpty(token) && stringRedisTemplate.hasKey(tokenKey)){
            //延长Redis中token的有效时间
            stringRedisTemplate.expire(tokenKey,RedisKey.TOKEN_EXPIRE, TimeUnit.SECONDS);
        }
    }
}
